<?php
header("Access-Control-Allow-Origin:*");
/**
 * 用户地址列表
 * @param unknown_type $pars
 * @throws Exception
 */
function addresslist($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?10:$pars->size;

		$sql="SELECT  a.*,m.addr_id as d from cw_address a
left join cw_member m on a.addr_id=m.addr_id and a.user_id=m.user_id
		where a.user_id=".$uid."  ORDER BY m.addr_id desc ,a.addr_id DESC limit $row,$size";
		$list=$db->getAll($sql);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 用户地址info
 * @param unknown_type $pars
 * @throws Exception
 */
function addressinfo($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$addrid=empty($pars->addrid)?0:intval($pars->addrid);
		if(empty($addrid)){
			throw new Exception('地址不存在');
		}
			
		$sql="SELECT  * from  cw_address  where addr_id=".$addrid."";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('地址不存在');
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 用户地址info
 * @param unknown_type $pars
 * @throws Exception
 */
function addaddress($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$addrid=empty($pars->addrid)?0:intval($pars->addrid);
		$consignee=empty($pars->consignee)? '':trim($pars->consignee);
		$regionid=empty($pars->regionid)?0:intval($pars->regionid);
		$regionname=empty($pars->regionname)? '':trim($pars->regionname);
		$address=empty($pars->address)? '':trim($pars->address);
		$zipcode=empty($pars->zipcode)?0:intval($pars->zipcode);
		$phonetel=empty($pars->phonetel)?0:trim($pars->phonetel);
		$phonemob =empty($pars->phonemob)?0:trim($pars->phonemob);
		if(empty($consignee)){
			throw new Exception("请填写联系人");
		}
		if(empty($regionid)||empty($regionname)){
			throw new Exception("请选择区域");
		}
		if(empty($address)){
			throw new Exception("请填写地址");
		}
			
		if(empty($phonetel)){
			throw new Exception("请填写联系电话");
		}
		if($addrid){//编辑
			$sql="update  cw_address set  consignee='$consignee',region_id='$regionid',region_name='$regionname',address='$address',zipcode='$zipcode'
			,zipcode='$zipcode',phone_tel='$phonetel'	where  addr_id=".$addrid;
			$s=$db->query($sql);
			$list=array('addr_id'=>$addr_id);

		}else{// 新增
			$sql="insert into cw_address(user_id,consignee,region_id,region_name,address,zipcode,phone_tel,phone_mob)
			                  values('$uid','$consignee','$regionid','$regionname','$address','$zipcode','$phonetel','$phonemob')";
			$db->query($sql);
			$addr_id=$db->insert_id();
			if($addr_id){
				$list=array('addr_id'=>$addr_id);
			}else {
				throw new Exception("地址新增失败");
			}
		}
		$status=1;

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 用户地址del
 * @param unknown_type $pars
 * @throws Exception
 */
function dropaddress($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$addrid=empty($pars->addrid)?0:intval($pars->addrid);
		if(empty($addrid)){
			throw new Exception('地址不存在');
		}
			
		$sql="delete  from  cw_address  where addr_id=".$addrid." and  user_id=".$uid;
		$list=$db->query($sql);
		if($list){
			$list='地址移除成功';
		}else{
			throw new Exception("地址移除失败");
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 商品分类
 * @param unknown_type $pars
 * @throws Exception
 */
function gcategory($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$pid=empty($pars->pid)?0:$pars->pid;

		$sql="select cate_id,cate_name from cw_gcategory where parent_id=".$pid." ORDER BY sort_order";
		$list=$db->getAll($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 广告
 * @param unknown_type $pars
 * @throws Exception
 */
function ad($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?5:$pars->size;
		$page=empty($pars->page)?'':$pars->page;
		$position=empty($pars->position)?'':$pars->position;

		$sql="select pic,title,type,outkey,url from cw_ad where is_show=1 and page='".$page."' and position='".$position."' order by sort_order limit $row,$size";
		$adlist=$db->getAll($sql);
		if($adlist){
			foreach ($adlist as $k=>$v){
				if($v['type']=='article'){
					$v['url']=site_url().'/m/index.php?app=article&id='.$v['outkey'];
				}
				$list[]=$v;
			}
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 首页商品列表
 * @param unknown_type $pars
 * @throws Exception
 */
function sysrecgoods($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?8:$pars->size;

		$sql="select goods_id,goods_name,price,default_image,old_price from cw_goods where sysrec=1 order by syssort limit $row,$size";
		$list=$db->getAll($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 商品搜索
 * Enter description here ...
 * @param unknown_type $pars
 */
function goodslist($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?8:$pars->size;

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		$scate_id = empty($pars->scate_id) ? 0 : intval($pars->scate_id);
		$stype = empty($pars->stype) ? 0 : intval($pars->stype);
		
		$rec = empty($pars->rec) ? 0 : intval($pars->rec);

		$keyword=empty($pars->keyword)?'':$pars->keyword;
		$brand=empty($pars->brand)?'':$pars->brand;
		$price1=!isset($pars->price1)?'-1':$pars->price1;
		$price2=empty($pars->price2)?'0':$pars->price2;
		$sort=empty($pars->sort)?'g.add_time':$pars->sort;
		$order=empty($pars->order)?'desc':$pars->order;
		$tag=empty($pars->tag)?'':$pars->tag;

		$attribute=empty($pars->goodstype)?'':$pars->goodstype;

		$conditions=' g.if_show = 1 AND g.closed = 0 ';
		// 分类
		$cate_id = empty($pars->cate_id) ? 0 : intval($pars->cate_id);
		if ($cate_id > 0){
			$cate_mod =& bm('gcategory');
			$cate_ids = $cate_mod->get_descendant_ids($cate_id);
			$conditions .= " AND g.cate_id" . db_create_in($cate_ids);
		}

		if($keyword){
			$conditions.=" and (g.goods_name REGEXP '".$keyword."' or g.tags REGEXP '".$keyword."'
			or g.brand REGEXP '".$keyword."' or s.store_name REGEXP '".$keyword."')";

			$sql="replace into cw_user_search set uid='".$pars->uid."',keyword='".$keyword."',sdate='".gmtime()."'";
			$db->query($sql);

			$sql="select count(1) from cw_user_search where uid='".$pars->uid."'";
			$c=$db->getOne($sql);
			if($c>20){
				$sql="delete from cw_user_search where uid='".$pars->uid."' order by sdate limit 1";
				$db->query($sql);
			}
		}

		$bconditions='';
		$bconditions=$conditions;
		if($brand){
			$list['usebrand']=$brand;
			$conditions.=" and brand='".$brand."'";
		}

		if($price1>=0&&$price1!=''){
			$list['price1']=$price1;
			$conditions.=" and price>=".$price1;
		}
		if($price2){
			$list['price2']=$price2;
			$conditions.=" and price<=".$price2;
		}

		if($store_id){
			$conditions.=" and g.store_id='".$store_id."'";
		}
		if($scate_id){
			$conditions.=" and EXISTS(SELECT 1 from cw_category_goods c where c.cate_id=".$scate_id." and c.goods_id=g.goods_id)";
		}
		if($rec){
			$conditions.=" and g.recommended=1";
		}

		if($stype==1){
			$conditions.=" and ".gmtime()."-g.add_time<=7*24*60*60";
		}elseif($stype==2){
			//$conditions.=" and g.recommended=1";
			$conditions.=" and 1<>1";
		}
		
		if($tag){
			$conditions.=" and g.tags REGEXP '".$tag."'";
		}
		
		if($attribute){
			$list['attribute']=$attribute;
			foreach ($attribute as $k=>$v){
				$conditions.=" and exists(select 1 from cw_goods_attr a where a.goods_id=g.goods_id and attr_id=".$v->attr_id." and attr_value='".$v->attr_value."')";
			}
		}

		$sql="select g.goods_id,goods_name,price,default_image,old_price,noshipfee,s.store_name,g.store_id,gs.sales,tags,brand from cw_goods g
LEFT JOIN cw_store s on g.store_id=s.store_id
LEFT JOIN cw_goods_statistics gs on g.goods_id=gs.goods_id where $conditions order by $sort $order limit $row,$size";

		$goods_list = $db->getAll($sql);
		foreach ($goods_list as $key => $goods){
			$goods['tags'] = trim($goods['tags'], ',');
			$list['goods'][]=$goods;
		}

		if($list['goods']){
			$sql="select brand,COUNT(1) as c from cw_goods g LEFT JOIN cw_store s on g.store_id=s.store_id where $bconditions GROUP BY brand ORDER BY brand";
			$brand = $db->getAll($sql);
			$list['brand']=$brand;

			$sql="select MAX(price) from cw_goods g LEFT JOIN cw_store s on g.store_id=s.store_id where $bconditions";
			$max = $db->getOne($sql);

			$price=array();
			$ged=8;
			if($max<600){
				$ged=4;
			}
			if($max<300){
				$ged=2;
			}
			$ge=intval($max/$ged);
			if($ge<=20){
				$p=array('min'=>0,'max'=>$max);
				$price[]=$p;
			}else{
				for($i=0;$i<$ged;$i++){
					$m=$i*$ge+$ge-1;
					if($i==$ged-1){
						$m=intval($max);
					}
					$p=array('min'=>$i*$ge,'max'=>$m);
					$price[]=$p;
				}
			}

			$list['price']=$price;
		}
		$status=1;
	}catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 商品明细
 * Enter description here ...
 * @param unknown_type $pars
 */
function goodsinfo($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$goods_id=empty($pars->goods_id)?0:$pars->goods_id;
		if(empty($goods_id)){
			throw new Exception('商品不存在');
		}

		$sql="select g.goods_id,goods_name,price,default_image,old_price,noshipfee,s.store_name,g.store_id,gs.sales,tags,brand,if_show,closed,
		cate_name,cate_id,g.description,spec_qty,spec_name_1,spec_name_2,
		s.description as sdescription,star,follow_id,default_spec,praise_rate from cw_goods g
LEFT JOIN cw_store s on g.store_id=s.store_id
LEFT JOIN cw_goods_statistics gs on g.goods_id=gs.goods_id 
LEFT JOIN cw_follow f on g.goods_id=f.outkey and f.type='goods' and f.uid=".$pars->uid." 
where g.goods_id='".$goods_id."'";

		$goods = $db->getRow($sql);
		if(empty($goods)){
			throw new Exception('商品不存在');
		}

		if(!$goods['if_show']){
			throw new Exception('商品已经下架');
		}

		if($goods['closed']){
			throw new Exception('商品已经被系统禁售');
		}
		$goods['tags'] = trim($goods['tags'], ',');

		$sql="select image_url,thumbnail from cw_goods_image where goods_id=".$goods_id." ORDER BY sort_order";
		$goods['images']=$db->getAll($sql);

		$comment=array();
		$sql="SELECT buyer_id, buyer_name,real_name,headimgurl, anonymous, evaluation_time, comment, evaluation,specification,evaluation_pic,credit_value from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id
LEFT JOIN cw_member m on o.buyer_id=m.user_id where g.goods_id=".$goods_id." order by evaluation_time desc limit 0,10";
		$c=$db->getAll($sql);
		foreach ($c as $k=>$v){
			$v['evaluation_time']=local_date('Y-m-d H:i',$v['evaluation_time']);
			$comment[]=$v;
		}

		$goods['comment']=$comment;

		$sql="SELECT count(1) from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id where g.goods_id=".$goods_id;
		$goods['commentcount']=$db->getOne($sql);

		$sql="select spec_id, spec_1,spec_2,price,stock,sku,old_price from cw_goods_spec where goods_id=".$goods_id;
		$goods['spec']=$db->getAll($sql);

		$sql="select sum(ifnull(quantity,0)) from cw_cart where user_id=".$pars->uid;
		$cart=$db->getOne($sql);
		if(empty($cart)){
			$cart=0;
		}
		$goods['cart']=$cart;

		$sql="select attr_name,attr_value from cw_goods_attr where goods_id=".$goods_id." ORDER BY sort_order";
		$attr=$db->getAll($sql);
		$goods['attr']=$attr;

		$list=$goods;

		$sql="update cw_goods_statistics set views=views+1 where goods_id=".$goods_id;
		$db->query($sql);

		$status=1;
	}catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 商品评论
 * @throws Exception
 */
function goodscomment($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?10:$pars->size;

		$goods_id=empty($pars->goods_id)?0:$pars->goods_id;
		if(empty($goods_id)){
			throw new Exception('商品不存在');
		}
		$comment=array();
		$sql="SELECT buyer_id, buyer_name,real_name,headimgurl, anonymous, evaluation_time, comment, evaluation,specification,evaluation_pic,credit_value from cw_order_goods g
INNER JOIN cw_order o on g.order_id=o.order_id
LEFT JOIN cw_member m on o.buyer_id=m.user_id where g.goods_id=".$goods_id." order by evaluation_time desc limit $row,$size";
		$comment=$db->getAll($sql);
		foreach ($comment as $k=>$v){
			$v['evaluation_time']=local_date('Y-m-d H:i',$v['evaluation_time']);
			$list[]=$v;
		}
		
		$status=1;
	}catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 商品规格
 * @throws Exception
 */
function goodsspec($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$goods_id=empty($pars->goods_id)?0:$pars->goods_id;
		if(empty($goods_id)){
			throw new Exception('商品不存在');
		}

		$sql="select spec_id, spec_1,spec_2,s.price,stock,sku,s.old_price,spec_qty,spec_name_1,spec_name_2 from cw_goods_spec s
		inner join cw_goods g on s.goods_id=g.goods_id
		where g.goods_id=".$goods_id;
		$list=$db->getAll($sql);

		$status=1;
	}catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 我的购物车
 * @param unknown_type $pars
 */
function cart($pars){
	$db =&db();
	$status=0;
	$list=array();
	try{
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$cartlist=array();
		$sql="select c.*,s.store_name from cw_cart c
LEFT JOIN cw_store s on c.store_id=s.store_id
 where c.user_id=".$pars->uid;
		$carts=$db->getAll($sql);

		if($carts){
			foreach ($carts as $k=>$v){
				$list[$v['store_id']]['goods'][]=$v;
				$list[$v['store_id']]['store_name']=$v['store_name'];
				$list[$v['store_id']]['store_id']=$v['store_id'];
			}
		}

		$cartlist['cart']=array_values($list);

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$cartlist['info']=$db->getRow($sql);

		$status=1;
	}catch (Exception $exp){
		$cartlist=$exp->getMessage();
	}
	return JSONResult($status,$cartlist,$pars);
}

/**
 * 添加购物车
 * @param unknown_type $pars
 * @throws Exception
 */
function addcart($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		$goods_id=empty($pars->goods_id)?0:intval($pars->goods_id);
		$spec_id=empty($pars->spec_id)?0:intval($pars->spec_id);
		$quantity=empty($pars->quantity)?1:intval($pars->quantity);

		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		if(empty($goods_id)||empty($spec_id)){
			throw new Exception('商品不存在');
		}

		$sql="select if_show,stock,closed,goods_name,gs.price,g.default_image,g.store_id,spec_name_1,spec_name_2,spec_1,spec_2,noshipfee from cw_goods g
		LEFT JOIN cw_goods_spec gs on g.goods_id=gs.goods_id where g.goods_id=".$goods_id." and spec_id=".$spec_id;
		$goods=$db->getRow($sql);

		if($goods){
			if(!$goods['if_show']){
				throw new Exception('商品已经下架');
			}
			if($goods['closed']){
				throw new Exception('商品已经禁售');
			}
			if($goods['stock']<$quantity){
				//throw new Exception('商品库存不足');
			}
		}else{
			throw new Exception('暂无此商品销售');
		}

		if($goods['store_id']==$pars->uid){
			throw new Exception('不能购买自己的商品');
		}

		$spec_1 = $goods['spec_name_1'] ? $goods['spec_name_1'] . ':' . $goods['spec_1'] : $goods['spec_1'];
		$spec_2 = $goods['spec_name_2'] ? $goods['spec_name_2'] . ':' . $goods['spec_2'] : $goods['spec_2'];

		$specification = $spec_1 . ' ' . $spec_2;

		$sql="select rec_id from cw_cart where user_id=".$pars->uid." and goods_id=".$goods_id." and spec_id='".$spec_id."'";
		$rec=$db->getOne($sql);
		if($rec){
			$sql="update cw_cart set quantity=quantity+".$quantity.",isorder=1 where rec_id=".$rec;

			$db->query($sql);
		}else{
			$sql="insert into cw_cart(user_id,goods_id,goods_name,price,quantity,goods_image,store_id,specification,spec_id,noshipfee)
		values('".$pars->uid."','".$goods_id."','".$goods['goods_name']."','".$goods['price']."','".$quantity."','".$goods['default_image']."',
		'".$goods['store_id']."','".$specification."','".$spec_id."','".$goods['noshipfee']."')";

			$db->query($sql);
			if(!$db->insert_id()){
				throw new Exception('添加购物车失败');
			}
		}

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$list=$db->getRow($sql);

		$sql="update cw_goods_statistics set carts=carts+1 where goods_id=".$goods_id;
		$db->query($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 编辑购物车
 * @param unknown_type $pars
 */
function editcart($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		$rec_id=empty($pars->rec_id)?0:intval($pars->rec_id);
		$quantity=empty($pars->quantity)?-1:intval($pars->quantity);
		$spec_id=empty($pars->spec_id)?0:intval($pars->spec_id);
		$isorder=!isset($pars->isorder)||$pars->isorder==''?-1:intval($pars->isorder);
		$tspec=$spec_id;

		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		if($quantity>0||$spec_id>0||$isorder>=0){

			$sql="select * from cw_cart where user_id=".$pars->uid." and rec_id=".$rec_id;
			$cart=$db->getRow($sql);
			if(empty($cart)){
				throw new Exception('购物车中无此商品');
			}
			$goods_id=$cart['goods_id'];
			if(empty($spec_id)){
				$spec_id=$cart['spec_id'];
			}

			$sql="select if_show,stock,closed,goods_name,gs.price,g.default_image,g.store_id,spec_name_1,spec_name_2,spec_1,spec_2 from cw_goods g
		LEFT JOIN cw_goods_spec gs on g.goods_id=gs.goods_id where g.goods_id=".$goods_id." and spec_id=".$spec_id;
			$goods=$db->getRow($sql);

			if($goods){
				if(!$goods['if_show']){
					throw new Exception('商品已经下架');
				}
				if($goods['closed']){
					throw new Exception('商品已经禁售');
				}
				if($quantity){
					if($goods['stock']<$quantity){
						//throw new Exception('商品库存不足');
					}
				}
			}else{
				throw new Exception('暂无此商品销售');
			}

			$sql="update cw_cart set";
			if($quantity>0){
				if($goods['stock']<$quantity){
					//throw new Exception('商品库存不足');
				}
				$sql.=" quantity=".$quantity.",";
			}
			if($tspec>0){
				if($goods['stock']<$cart['quantity']){
					//throw new Exception('商品库存不足');
				}

				$spec_1 = $goods['spec_name_1'] ? $goods['spec_name_1'] . ':' . $goods['spec_1'] : $goods['spec_1'];
				$spec_2 = $goods['spec_name_2'] ? $goods['spec_name_2'] . ':' . $goods['spec_2'] : $goods['spec_2'];

				$specification = $spec_1 . ' ' . $spec_2;
				$sql.=" spec_id=".$spec_id.",price=".$goods['price'].",specification='".$specification."',";
			}
			if($isorder>=0){
				$sql.=" isorder=".$isorder.",";
			}
			$sql=trim($sql,',');
			$sql.=" where rec_id=".$rec_id;


			$db->query($sql);
		}

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$list=$db->getRow($sql);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 全选或不选购物车
 * @param unknown_type $pars
 * @throws Exception
 */
function allchoosecart($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		$isorder=empty($pars->isorder)?0:intval($pars->isorder);
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);

		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$sqlw="1=1";
		if($store_id){
			$sqlw.=" and store_id=".$store_id;
		}

		$sql="update cw_cart set isorder=".$isorder." where user_id=".$pars->uid." and $sqlw";
		$db->query($sql);

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$list=$db->getRow($sql);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 删除购物车
 * @param unknown_type $pars
 */
function delcart($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		$rec_id=empty($pars->rec_id)?0:trim($pars->rec_id,',');
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		if(empty($rec_id)){
			throw new Exception('没有选择任何商品');
		}

		$sql="delete from cw_cart where user_id=".$pars->uid." and rec_id in (".$rec_id.")";
		$db->query($sql);

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$list=$db->getRow($sql);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 购车信息
 * @param unknown_type $pars
 */
function cartinfo($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantitys from yk_cart where user_id=".$pars->uid." and isorder=1";
		$list=$db->getRow($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 支付方式
 * @param unknown_type $pars
 * @throws Exception
 */
function payment($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$sqlw=" 1=1";
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if($store_id){
			$sqlw.=" and store_id=".$store_id;
		}

		$sql="select * from cw_payment where enabled=1 and $sqlw ORDER BY sort_order";
		$list=$db->getAll($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 下单前准备（购物结算）
 * @param unknown_type $pars
 * @throws Exception
 */
function orderpre($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$list['addr']=array();
		$sql="select addr_id from cw_member where user_id=".$pars->uid;
		$addr_id=$db->getOne($sql);
		if($addr_id){
			$sql="SELECT * from cw_address where addr_id=".$addr_id;
			$addr=$db->getRow($sql);
			$list['addr']=$addr;
		}

		if(empty($list['addr'])){
			$sql="SELECT * from cw_address where user_id=".$pars->uid." order by addr_id desc limit 1";
			$addr=$db->getRow($sql);
			$list['addr']=$addr;
		}

		$sql="select c.*,s.store_name from cw_cart c
				LEFT JOIN cw_store s on c.store_id=s.store_id
				 where c.user_id=".$pars->uid." and isorder=1";
		$carts=$db->getAll($sql);
		if(empty($carts)){
			throw new Exception('购车没有可结算的商品');
		}
		$shipfee=0;
		$temp=array();
		foreach ($carts as $k=>$v){
			$temp[$v['store_id']]['goods'][]=$v;
			$temp[$v['store_id']]['store_name']=$v['store_name'];
			$temp[$v['store_id']]['store_id']=$v['store_id'];

			$sql="select shipping_id,shipping_name,shipping_desc,first_price,step_price,cod_regions from cw_shipping
			where store_id=".$v['store_id']." and enabled=1 ORDER BY sort_order";			
			$shipping=$db->getAll($sql);

			if(empty($shipping)){
				throw new Exception($v['store_name'].' 没有配送方式，无法下单');
			}
			$temp[$v['store_id']]['shipping']=$shipping;

			$sql="select e.shipping_id,s.first_price,s.step_price from cw_order o
					INNER JOIN cw_order_extm e on o.order_id=e.order_id 
					INNER JOIN cw_shipping s on e.shipping_id=s.shipping_id
					where buyer_id=".$pars->uid." and seller_id=".$v['store_id']." ORDER BY o.add_time desc limit 1";
			$defaultship=$db->getRow($sql);

			if(empty($defaultship)){
				$defaultship=$shipping[0];
			}

			$sql="select count(1) from cw_cart where noshipfee=0 and store_id=".$v['store_id']." and user_id=".$pars->uid;
			$can=$db->getOne($sql);
			if($can){
				$shipfee+=$defaultship['first_price'];
			}
			$temp[$v['store_id']]['defaultship']=$defaultship['shipping_id'];

			$temp[$v['store_id']]['noshipfee']=$can==0?1:0;
		}

		$list['cart']=array_values($temp);
		$list['shipfee']=$shipfee;

		$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount, sum(ifnull(quantity,0)) as quantity from cw_cart where user_id=".$pars->uid." and isorder=1";
		$info=$db->getRow($sql);

		$list['amount']=$info['amount'];
		$list['quantity']=$info['quantity'];

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 立即购买（购物结算）
 * @param unknown_type $pars
 * @throws Exception
 */
function fastorderpre($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$goods_id=empty($pars->goods_id)?0:intval($pars->goods_id);
		$spec_id=empty($pars->spec_id)?0:intval($pars->spec_id);
		$quantity=empty($pars->quantity)?1:intval($pars->quantity);

		if(empty($goods_id)||empty($spec_id)){
			throw new Exception('商品不存在');
		}

		$sql="select if_show,stock,closed,goods_name,gs.price,g.default_image,g.store_id,spec_id,g.goods_id,spec_name_1,spec_name_2,spec_1,spec_2,noshipfee,s.store_name from cw_goods g
		LEFT JOIN cw_goods_spec gs on g.goods_id=gs.goods_id 
		LEFT JOIN cw_store s on g.store_id=s.store_id
		where g.goods_id=".$goods_id." and spec_id=".$spec_id;
		$goods=$db->getRow($sql);

		if($goods){
			if(!$goods['if_show']){
				throw new Exception('商品已经下架');
			}
			if($goods['closed']){
				throw new Exception('商品已经禁售');
			}
			if($goods['stock']<$quantity){
				//throw new Exception('商品库存不足');
			}
		}else{
			throw new Exception('暂无此商品销售');
		}

		if($goods['store_id']==$pars->uid){
			throw new Exception('不能购买自己的商品');
		}

		$spec_1 = $goods['spec_name_1'] ? $goods['spec_name_1'] . ':' . $goods['spec_1'] : $goods['spec_1'];
		$spec_2 = $goods['spec_name_2'] ? $goods['spec_name_2'] . ':' . $goods['spec_2'] : $goods['spec_2'];

		$specification = $spec_1 . ' ' . $spec_2;

		$list['addr']=array();
		$sql="select addr_id from cw_member where user_id=".$pars->uid;
		$addr_id=$db->getOne($sql);
		if($addr_id){
			$sql="SELECT * from cw_address where addr_id=".$addr_id;
			$addr=$db->getRow($sql);
			$list['addr']=$addr;
		}

		if(empty($list['addr'])){
			$sql="SELECT * from cw_address where user_id=".$pars->uid." order by addr_id desc limit 1";
			$addr=$db->getRow($sql);
			$list['addr']=$addr;
		}

		$goods=array(
			'rec_id'=>'0',
			'user_id'=>$pars->uid,
			'session_id'=>'',
			'store_id'=>$goods['store_id'],
			'goods_id'=>$goods['goods_id'],
			'goods_name'=>$goods['goods_name'],
			'spec_id'=>$goods['spec_id'],
			'specification'=>$specification,
			'price'=>$goods['price'],
			'quantity'=>$quantity,
			'goods_image'=>$goods['default_image'],
			'isorder'=>'1',
			'noshipfee'=>$goods['noshipfee'],
			'store_name'=>$goods['store_name'],
		);

		$shipfee=0;
		$temp=array();
		$carts=array();
		$carts[]=$goods;
		foreach ($carts as $k=>$v){
			$temp[$v['store_id']]['goods'][]=$v;
			$temp[$v['store_id']]['store_name']=$v['store_name'];
			$temp[$v['store_id']]['store_id']=$v['store_id'];

			$sql="select shipping_id,shipping_name,shipping_desc,first_price,step_price,cod_regions from cw_shipping
			where store_id=".$v['store_id']." and enabled=1 ORDER BY sort_order";			
			$shipping=$db->getAll($sql);

			if(empty($shipping)){
				throw new Exception($v['store_name'].' 没有配送方式，无法下单');
			}
			$temp[$v['store_id']]['shipping']=$shipping;

			$sql="select e.shipping_id,s.first_price,s.step_price from cw_order o
INNER JOIN cw_order_extm e on o.order_id=e.order_id 
INNER JOIN cw_shipping s on e.shipping_id=s.shipping_id
where buyer_id=".$pars->uid." and seller_id=".$v['store_id']." ORDER BY o.add_time desc limit 1";
			$defaultship=$db->getRow($sql);

			if(empty($defaultship)){
				$defaultship=$shipping[0];
			}

			if(!$v['noshipfee']){
				$shipfee+=$defaultship['first_price'];
			}
			$temp[$v['store_id']]['defaultship']=$defaultship['shipping_id'];

			$temp[$v['store_id']]['noshipfee']=$v['noshipfee']==1?1:0;
		}

		$list['cart']=array_values($temp);
		$list['shipfee']=$shipfee;

		$list['amount']=$goods['price']*$quantity;
		$list['quantity']=$quantity;

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 确认订单
 * @param unknown_type $pars
 */
function orderadd($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);

		$sql="select user_id,user_name,real_name,email from cw_member where user_id=".$pars->uid;
		$user=$db->getRow($sql);
		if(empty($user)){
			throw new Exception('当前人员不存在');
		}

		$postscript=empty($pars->postscript)?'':$pars->postscript;

		$goods_id=empty($pars->goods_id)?0:intval($pars->goods_id);
		$spec_id=empty($pars->spec_id)?0:intval($pars->spec_id);
		$quantity=empty($pars->quantity)?1:intval($pars->quantity);

		$payment_id=empty($pars->payment_id)?0:intval($pars->payment_id);
		if(empty($payment_id)){
			throw new Exception('请选择有效的支付方式');
		}
		$sql="select * from cw_payment where enabled=1 and payment_id=".$payment_id;
		$payment=$db->getRow($sql);
		if(empty($payment)){
			throw new Exception('请选择有效的支付方式');
		}
		$coupon_sn=empty($pars->coupon)?'':$pars->coupon; //优惠券
		$ship=empty($pars->ship)?'':$pars->ship;
		if(empty($payment_id)){
			throw new Exception('请选择有效的配送方式');
		}

		$addr_id=empty($pars->addr_id)?0:intval($pars->addr_id);
		$sql="SELECT * from cw_address where addr_id=".$addr_id." and user_id=".$pars->uid;
		$addr=$db->getRow($sql);
		if(!$addr){
			throw new Exception('请选择有效的配送地址');
		}

		$amount=0;
		$quantity1=0;
		$shipfee=0;
		if($goods_id&&$spec_id){
			$sql="select if_show,stock,closed,goods_name,gs.price,g.default_image,g.store_id,spec_id,g.goods_id,spec_name_1,spec_name_2,spec_1,spec_2,noshipfee,s.store_name from cw_goods g
		LEFT JOIN cw_goods_spec gs on g.goods_id=gs.goods_id 
		LEFT JOIN cw_store s on g.store_id=s.store_id
		where g.goods_id=".$goods_id." and spec_id=".$spec_id;
			$goods=$db->getRow($sql);

			if($goods){
				if(!$goods['if_show']){
					throw new Exception('商品已经下架');
				}
				if($goods['closed']){
					throw new Exception('商品已经禁售');
				}
				if($goods['stock']<$quantity){
					//throw new Exception('商品库存不足');
				}
			}else{
				throw new Exception('暂无此商品销售');
			}

			if($goods['store_id']==$pars->uid){
				throw new Exception('不能购买自己的商品');
			}

			$spec_1 = $goods['spec_name_1'] ? $goods['spec_name_1'] . ':' . $goods['spec_1'] : $goods['spec_1'];
			$spec_2 = $goods['spec_name_2'] ? $goods['spec_name_2'] . ':' . $goods['spec_2'] : $goods['spec_2'];

			$specification = $spec_1 . ' ' . $spec_2;

			$goods=array(
				'rec_id'=>'0',
				'user_id'=>$pars->uid,
				'session_id'=>'',
				'store_id'=>$goods['store_id'],
				'goods_id'=>$goods['goods_id'],
				'goods_name'=>$goods['goods_name'],
				'spec_id'=>$goods['spec_id'],
				'specification'=>$specification,
				'price'=>$goods['price'],
				'quantity'=>$quantity,
				'goods_image'=>$goods['default_image'],
				'isorder'=>'1',
				'noshipfee'=>$goods['noshipfee'],
				'store_name'=>$goods['store_name'],
			);

			$shipping_id=0;
			$shipping=array();
			$hasship=false;
			foreach ($ship as $k=>$v){
				if($v->store_id==$goods['store_id']){
					$hasship=true;
					$shipping_id=empty($v->shipping_id)?0:intval($v->shipping_id);
					$sql="select shipping_id,shipping_name,shipping_desc,first_price,step_price,cod_regions from cw_shipping
			where store_id=".$v->store_id." and enabled=1 and shipping_id=".$shipping_id;			
					$shipping=$db->getRow($sql);

					if(empty($shipping)){
						throw new Exception('请选择有效的配送方式');
					}
					break;
				}
			}
			if(!$hasship){
				throw new Exception('请选择有效的配送方式');
			}
			if(!$goods['noshipfee']){
				$shipfee+=$shipping['first_price'];
			}

			$list[$goods['store_id']]['goods'][]=$goods;
			$list[$goods['store_id']]['shipfee']=$shipfee;
			$list[$goods['store_id']]['shipping']=$shipping;
			$list[$goods['store_id']]['store_name']=$goods['store_name'];
			$list[$goods['store_id']]['store_id']=$goods['store_id'];

			$list[$goods['store_id']]['amount']=$goods['price']*$goods['quantity'];
		}else{
			$sql="select c.*,s.store_name from cw_cart c
LEFT JOIN cw_store s on c.store_id=s.store_id
 where c.user_id=".$pars->uid." and isorder=1";
			$carts=$db->getAll($sql);

			if(!$carts){
				throw new Exception('购车没有可结算的商品');
			}

			foreach ($carts as $k=>$v){
				$list[$v['store_id']]['goods'][]=$v;
				$list[$v['store_id']]['store_name']=$v['store_name'];
				$list[$v['store_id']]['store_id']=$v['store_id'];

				$shipping_id=0;
				$shipping=array();
				$hasship=false;
				foreach ($ship as $kk=>$vv){
					if($vv->store_id==$v['store_id']){
						$hasship=true;
						$shipping_id=empty($vv->shipping_id)?0:intval($vv->shipping_id);
						$sql="select shipping_id,shipping_name,shipping_desc,first_price,step_price,cod_regions from cw_shipping
			where store_id=".$vv->store_id." and enabled=1 and shipping_id=".$shipping_id;			
						$shipping=$db->getRow($sql);

						if(empty($shipping)){
							throw new Exception('请选择有效的配送方式');
						}
						break;
					}
				}
				if(!$hasship){
					throw new Exception('请选择有效的配送方式');
				}

				$sql="select count(1) from cw_cart where noshipfee=0 and store_id=".$v['store_id']." and user_id=".$pars->uid;
				$can=$db->getOne($sql);
				if($can){
					$shipfee=$shipping['first_price'];
				}
				$list[$v['store_id']]['shipfee']=$shipfee;
				$list[$v['store_id']]['shipping']=$shipping;

				$sql="select sum(ifnull(quantity,0)*ifnull(price,0)) as amount from cw_cart where user_id=".$pars->uid." and store_id=".$v['store_id']." and isorder=1";
				$amount=$db->getOne($sql);
				$list[$v['store_id']]['amount']=$amount;
			}
		}

		$buyer_name=$user['real_name']?$user['real_name']:$user['user_name'];

		$order_id=0;
		$order_sn=gen_order_sn();
		foreach ($list as $k=>$v){
			$sql="insert into cw_order set
				order_sn='".$order_sn."',
				seller_id='".$v['store_id']."',
				seller_name='".$v['store_name']."',
				buyer_id='".$user['user_id']."',
				buyer_name='".$buyer_name."',
				buyer_email='".$user['email']."',
				status='".ORDER_PENDING."',
				add_time='".gmtime()."',
				payment_id='".$payment['payment_id']."',
				payment_name='".$payment['payment_name']."',
				payment_code='".$payment['payment_code']."',
				goods_amount='".$v['amount']."',
				postscript='".$postscript."',
				order_amount='".($v['amount']+$v['shipfee'])."'";

			$db->query($sql);
			$order_id=$db->insert_id();
			if(!$order_id){
				throw new Exception('提交订单失败');
			}
			foreach ($v['goods'] as $kg=>$vg){
				$sql="insert into cw_order_goods set
						goods_id='".$vg['goods_id']."',
						spec_id='".$vg['spec_id']."',
						specification='".$vg['specification']."',
						goods_name='".$vg['goods_name']."',
						price='".$vg['price']."',
						quantity='".$vg['quantity']."',
						goods_image='".$vg['goods_image']."',
						order_id='".$order_id."'";	
				$db->query($sql);

				//扣减库存
				//$sql="update cw_goods_spec set stock=stock-".$vg['quantity']." where spec_id=".$vg['spec_id'];
				//$db->query($sql);

				$sql="update cw_goods_statistics set orders=orders+1 where goods_id=".$vg['goods_id'];
				$db->query($sql);
			}

			$sql="insert into cw_order_extm set
					order_id='".$order_id."',
					consignee='".$addr["consignee"]."',
					region_id='".$addr["region_id"]."',
					region_name='".$addr["region_name"]."',
					address='".$addr["address"]."',
					zipcode='".$addr["zipcode"]."',
					phone_tel='".$addr["phone_tel"]."',
					phone_mob='".$addr["phone_mob"]."',
					shipping_id='".$v['shipping']["shipping_id"]."',
					shipping_name='".$v['shipping']["shipping_name"]."',
					shipping_fee='".$v['shipping']["first_price"]."'";

			$db->query($sql);

			order_progress($order_id,'已提交','待付款',$user['user_id'],'用户提交新订单');

			$sql="update cw_member set addr_id=".$addr_id." where user_id=".$uid;
			$db->query($sql);
		}

		if(!$goods_id&&!$spec_id){
			$sql="delete from cw_cart where user_id=".$pars->uid." and isorder=1";
			$db->query($sql);
		}

		$list=array("order_id"=>$order_id,'order_sn'=>$order_sn);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 店铺信息
 * @param unknown_type $pars
 * @throws Exception
 */
function storeinfo($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('店铺不存在');
		}

		$sql="select state,close_reason,store_id,store_name,owner_name,region_name,address,tel,store_banner,store_logo,description,star,praise_rate,follow_id from cw_store s
LEFT JOIN cw_follow f on s.store_id=f.outkey and f.type='store' and f.uid=$pars->uid
where store_id=$store_id";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('店铺不存在');
		}

		if($list['state']!=1){
			throw new Exception('店铺因:'.$list['close_reason']." 已关闭");
		}

		$sql="SELECT count(1) from cw_goods where store_id=$store_id and if_show=1 and closed=0";
		$list['goods_all']=$db->getOne($sql);

		$sql="SELECT count(1) from cw_goods where store_id=$store_id and if_show=1 and closed=0 and ".gmtime()."-add_time<=7*24*60*60";
		$list['goods_new']=$db->getOne($sql);

		$list['goods_discount']=0;

		$sql="SELECT count(1) from cw_gcategory where store_id=$store_id and if_show=1";
		$list['store_cate']=$db->getOne($sql);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 获取商家分类
 * @param unknown_type $pars
 * @throws Exception
 */
function storecate($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('店铺不存在');
		}

		$sql="SELECT cate_id,cate_name from cw_gcategory where store_id=$store_id and if_show=1 ORDER BY sort_order";
		$cates=$db->getAll($sql);
		foreach ($cates as $k=>$v){
			$sql="SELECT count(1) from cw_goods g where store_id=$store_id and EXISTS(SELECT 1 from cw_category_goods c where c.cate_id=".$v['cate_id'] ." and c.goods_id=g.goods_id)";
			$v['goods_num']=$db->getOne($sql);
			$list[]=$v;
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 我的订单列表
 * @param unknown_type $pars
 * @throws Exception
 */
function orderlist($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$row=empty($pars->row)?0:intval($pars->row);
		$size=empty($pars->size)?10:intval($pars->size);
		$status=empty($pars->status)?'':$pars->status;


		$conditions=" 1=1 and buyer_id=".$pars->uid;
		$orderd="add_time DESC";
		if($status){
			$conditions.=" and status='".order_status_translator($pars->status)."'";
			if($pars->status=='finished'){
				$conditions.=" and evaluation_status=0";
			}
		}

		$sql="select o.order_id,order_sn,status,o.add_time,order_amount,e.consignee,e.address,e.phone_tel,e.phone_mob,e.region_name,e.zipcode,
		seller_name as store_name,o.seller_id as store_id,evaluation_status,evaluation_time,invoice_no,shipping_fee,payment_id
		 from cw_order o 
		 INNER JOIN cw_order_extm e on o.order_id=e.order_id 
		 where $conditions ORDER BY $orderd limit $row,$size";

		$orders=$db->getAll($sql);
		foreach ($orders as $k=>$v){
			$v['evaluation_time']=local_date('Y-m-d H:i:s',$v['evaluation_time']);
			$v['add_time']=local_date('Y-m-d H:i:s',$v['add_time']);
			$v['status']=order_status($v['status']);
			$sql="select rec_id,goods_id,goods_name,goods_image,specification,price,quantity from cw_order_goods where order_id=".$v['order_id'];
			$v['goods']=$db->getAll($sql);
			$list[]=$v;
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 获取分类
 * @param unknown_type $pars
 * @throws Exception
 */
function attribute($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$cate_id=empty($pars->cate_id)?0:intval($pars->cate_id);
		if(empty($cate_id)){
			throw new Exception('分类不存在');
		}

		$sql="select attr_id,attr_name,def_value from cw_gcategory g INNER JOIN cw_attribute a on FIND_IN_SET(a.attr_id,g.attribute)
		WHERE cate_id=".$cate_id." and input_mode='select' ORDER BY a.sort_order";
		$attributes=$db->getAll($sql);

		foreach ($attributes as $k=>$v){
			$v['def_value']=str_replace(PHP_EOL, ',', $v['def_value']);
			$list[]=$v;
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 我的订单明细
 * @param unknown_type $pars
 * @throws Exception
 */
function orderinfo($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$order_id=empty($pars->order_id)?0:intval($pars->order_id);
		if(empty($order_id)){
			throw new Exception('订单不存在');
		}


		$conditions=" 1=1 and buyer_id=".$pars->uid." and o.order_id=".$order_id;

		$sql="select o.order_id,order_sn,status,o.add_time,order_amount,e.consignee,e.address,e.phone_tel,e.phone_mob,e.region_name,e.zipcode,
		seller_name as store_name,o.seller_id as store_id,payment_id,payment_name,pay_time,ship_time,finished_time,evaluation_status,evaluation_time,invoice_no,shipping_fee
		 from cw_order o 
		 INNER JOIN cw_order_extm e on o.order_id=e.order_id 
		 where $conditions";

		$orders=$db->getRow($sql);
		if(empty($orders)){
			throw new Exception('订单不存在');
		}

		if($orders['pay_time']){
			$orders['pay_time']=local_date('Y-m-d H:i:s',$orders['pay_time']);
		}
		if($orders['ship_time']){
			$orders['ship_time']=local_date('Y-m-d H:i:s',$orders['ship_time']);
		}
		if($orders['finished_time']){
			$orders['finished_time']=local_date('Y-m-d H:i:s',$orders['finished_time']);
		}
		if($orders['evaluation_time']){
			$orders['evaluation_time']=local_date('Y-m-d H:i:s',$orders['evaluation_time']);
		}
		$orders['add_time']=local_date('Y-m-d H:i:s',$orders['add_time']);
		$orders['status']=order_status($orders['status']);
		$sql="select rec_id,goods_id,goods_name,goods_image,price,spec_id,specification,quantity,evaluation from cw_order_goods where order_id=".$order_id;
		$orders['goods']=$db->getAll($sql);

		$sql="select operator,order_status,changed_status,remark,log_time from cw_order_log where order_id=".$order_id;
		$log=$db->getAll($sql);
		if($log){
			foreach ($log as $k=>$v){
				$v['log_time']=local_date('Y-m-d H:i:s',$v['log_time']);
				$orders['log'][]=$v;
			}
		}

		$list=$orders;

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 取消订单
 * @param unknown_type $pars
 * @throws Exception
 */
function ordercancel($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$order_id=empty($pars->order_id)?0:intval($pars->order_id);
		if(empty($order_id)){
			throw new Exception('订单不存在');
		}

		$conditions=" 1=1 and buyer_id=".$pars->uid." and order_id=".$order_id;

		$sql="select order_id,order_sn,status from cw_order where $conditions";

		$order=$db->getRow($sql);
		if(empty($order)){
			throw new Exception('订单不存在');
		}

		if($order['status']!=ORDER_SUBMITTED&&$order['status']!=ORDER_PENDING){
			throw new Exception('订单不能取消');
		}

		$sql="update cw_order set status='".ORDER_CANCELED."' where order_id=".$order_id;
		$db->query($sql);

		if($db->affected_rows()){
			order_progress($order_id,order_status($order['status']),'已取消',$pars->uid,'用户已经取消订单');
		}else{
			throw new Exception('取消订单失败');
		}

		$list='取消订单成功';

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 删除订单
 * @param unknown_type $pars
 * @throws Exception
 */
function orderdel($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$order_id=empty($pars->order_id)?0:intval($pars->order_id);
		if(empty($order_id)){
			throw new Exception('订单不存在');
		}

		$conditions=" 1=1 and buyer_id=".$pars->uid." and order_id=".$order_id;

		$sql="select order_id,order_sn,status from cw_order where $conditions";

		$order=$db->getRow($sql);
		if(empty($order)){
			throw new Exception('订单不存在');
		}

		if($order['status']!=ORDER_CANCELED){
			throw new Exception('订单不能删除');
		}

		$sql="delete from cw_order where order_id=".$order_id;
		$db->query($sql);

		if($db->affected_rows()){

			$sql="delete from cw_order_goods where order_id=".$order_id;
			$db->query($sql);

			$sql="delete from cw_order_extm where order_id=".$order_id;
			$db->query($sql);

			$sql="delete from cw_order_log where order_id=".$order_id;
			$db->query($sql);
		}else{
			throw new Exception('删除订单失败');
		}

		$list='删除订单成功';

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 在线支付回调
 * @param unknown_type $pars
 * @param unknown_type $total_fee
 * @throws Exception
 */
function orderonlinepay($pars){
	$status=0;
	try{
		$db=&db();
		$out_trade_no=empty($pars->out_trade_no)?'':$pars->out_trade_no;
		$payment_id=empty($pars->payment_id)?'':$pars->payment_id;
		$total_fee=empty($pars->total_fee)?0:floatval($pars->total_fee);
		$trade_no=empty($pars->trade_no)?0:floatval($pars->trade_no);

		if(empty($out_trade_no)){
			throw new Exception('无效的订单');
		}
		if(empty($total_fee)){
			throw new Exception('无效的费用');
		}


		if(empty($payment_id)){
			throw new Exception('无效的支付方式');
		}
		$sql="select * from cw_payment where enabled=1 and payment_id=".$payment_id;
		$payment=$db->getRow($sql);
		if(empty($payment)){
			throw new Exception('无效的支付方式');
		}

		if($payment['微信']=='微信'){
			$total_fee=$total_fee/100;
		}

		$orderself=array();
		$sql="select * from cw_order where order_sn='".$out_trade_no."'";

		$orderself=$db->getRow($sql);
		if($total_fee<$orderself['order_amount']){
			throw new Exception('支付金额错误');
		}

		if(empty($orderself)){
			throw new Exception('无效的订单');
		}
		if($orderself['status']!=ORDER_PENDING){
			$list='支付成功';
			$status=1;
		}else{
			$list=$orderself;
			$o_tid=$orderself['order_id'];

			$sql="update cw_order set status='".ORDER_ACCEPTED."',payment_name='".$payment['payment_name']."',payment_id='".$payment['payment_id']."',
			payment_code='".$payment['payment_code']."',out_trade_sn='".$trade_no."',pay_time='".gmtime()."' where order_id=".$o_tid;
			$db->query($sql);

			if(!$db->affected_rows()){
				throw new Exception('支付订单失败');
			}
			order_progress($o_tid,'待付款','已付款',$list['buyer_id'],'用户已经支付订单');
			$list='支付成功';
			$status=1;
		}
	}
	catch (Exception $exp){
		$msg=str_replace('\"', '\'', $exp->getMessage());
		$list=$msg;
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 评论商品
 * @param unknown_type $pars
 */
function comment($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$rec_id=empty($pars->rec_id)?0:intval($pars->rec_id);
		$credit_value=empty($pars->credit_value)?5:intval($pars->credit_value);
		$comment=empty($pars->comment)?'':$pars->comment;
		$evaluation_pic=empty($pars->evaluation_pic)?'':$pars->evaluation_pic;
		$anonymous=empty($pars->anonymous)?1:intval($pars->anonymous);
		if(empty($rec_id)){
			throw new Exception('商品不存在');
		}

		$sql="select o.evaluation_status,o.evaluation_time,g.evaluation,g.`comment`,
		g.evaluation_pic,g.credit_value,goods_id,status,g.order_id,seller_id from cw_order_goods g
inner JOIN cw_order o on g.order_id=o.order_id
 where rec_id=".$rec_id." and buyer_id=".$pars->uid;

		$order=$db->getRow($sql);
		if(empty($order)){
			throw new Exception('你没有购买此商品');
		}

		if($order['status']!=ORDER_FINISHED){
			throw new Exception('你还不能评价此商品');
		}

		if(empty($comment)){
			throw new Exception('请输入你的评价');
		}

		if(strlen($comment)<20||strlen($comment)>250){
			throw new Exception('请输入20到250个字符');
		}

		if($evaluation_pic){
			$sql="update cw_order_goods set evaluation=1,comment='".$comment."',evaluation_pic='".$evaluation_pic."',credit_value='".$credit_value."'
		 where rec_id=".$rec_id;
		}else{
			$sql="update cw_order_goods set evaluation=1,comment='".$comment."',credit_value='".$credit_value."'
		 where rec_id=".$rec_id;
		}
		$db->query($sql);

		if(!$order['evaluation']){
			$sql="update cw_goods_statistics set comments=comments+1 where goods_id=".$order['goods_id'];
			$db->query($sql);
		}

		$sql="select count(1) from cw_order_goods where order_id=".$order['order_id']." and evaluation=0";
		$un=$db->getOne($sql);
		if(empty($un)){
			$sql="update cw_order set evaluation_status=1,evaluation_time='".gmtime()."',anonymous=".$anonymous." where order_id=".$order['order_id'];
			$db->query($sql);
		}

		updatestore($order['seller_id']);
		$list='评价商品成功';

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 确认收货
 * @param unknown_type $pars
 */
function orderfinish($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$order_id=empty($pars->order_id)?0:intval($pars->order_id);
		if(empty($order_id)){
			throw new Exception('订单不存在');
		}

		$sql="select * from cw_order where order_id=".$order_id." and buyer_id=".$pars->uid;

		$order=$db->getRow($sql);
		if(empty($order)){
			throw new Exception('订单不存在');
		}

		if($order['status']!=ORDER_SHIPPED){
			throw new Exception('你还不能确认收货');
		}


		$sql="update cw_order set status=".ORDER_FINISHED.",finished_time='".gmtime()."' where order_id=".$order_id;

		$db->query($sql);

		order_progress($order_id,'已发货','已完成',$order['buyer_id'],'用户已经确认,订单已完成');

		$list='确认收货成功,订单已完成,您还可以评价商品';

		$sql="select goods_id from cw_order_goods where order_id=".$order_id;
		$goods=$db->getAll($sql);
		if($goods){
			foreach ($goods as $k=>$v){
				$sql="update cw_goods_statistics set sales=sales+1 where goods_id=".$v['goods_id'];
				$db->query($sql);
			}
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
?>